<template>
  <div>
    <Spin fix v-if="ifSpin">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>附件下载中</div>
    </Spin>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <div v-if="switchFlag">
        <Row :gutter="16" class="query-form" >
          <i-col span="8">
            <FormItem label="创建人姓名：">
              <Input  class='' type='text' v-model='dataToQuery.userName'></Input>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="活动主题：">
              <Select v-model="dataToQuery.topicActivityId" filterable>
                <Option v-for="item in reqTopics" :value="item.topicActivityId" :key="item.topicActivityId">{{ item.themeName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="创建时间：">
              <DatePicker v-model="dataToQuery.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择创建时间（开始，结束）"></DatePicker>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16" class="query-form2">
          <i-col span="8">
            <FormItem label="所属单位：">
              <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                           :orgTree="true"></cascaderDom>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="所属二级集团：">
              <Select v-model="dataToQuery.twoLevelOrgId" filterable>
                <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query"  icon="md-search"  @click="query1">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reseter">重置</Button>
              <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
            </div>
          </i-col>
        </Row>
      </div>
      <div v-else>
        <Row :gutter="16" class="query-form2">
          <i-col span="8">
            <FormItem label="创建人姓名：">
              <Input  class='' type='text' v-model='dataToQuery.userName'></Input>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="活动主题：">
              <Select v-model="dataToQuery.topicActivityId" filterable>
                <Option v-for="item in reqTopics" :value="item.topicActivityId" :key="item.topicActivityId">{{ item.themeName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reseter">重置</Button>
              <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
            </div>
          </i-col>
        </Row>
      </div>
    </Form>
    <Row type="flex" justify="start" class="query-form">
      <i-col>
        <Button class="ivu-btn-add" v-if="reqTopics.length > 0" @click="downloadTemplate">下载模板</Button>
        <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
        <Button :loading="buttonLoading" class="ivu-btn-add" @click="batchDownload">批量下载</Button>
      </i-col>
    </Row>
    <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
           :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
    <Row type="flex" justify="end" >
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
      </i-col>
    </Row>
    <Modal v-model="modal1" width="1200" :mask-closable="false" :title="'填报' + titleName">
      <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="活动主题：" prop="topicActivityId">
              <Select v-model="formData.topicActivityId"  @on-change="changeActivity" filterable>
                <Option v-for="item in topics" :value="item.topicActivityId" :key="item.topicActivityId">{{ item.themeName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="编制时间：" prop="createDateStr">
              <Input v-model="formData.createDateStr" readonly />
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="创建人：" prop="userName">
              <Input v-model="formData.userName" readonly/>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="联系电话：" prop="mobileNumber">
              <Input v-model="formData.mobileNumber" />
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="创建时间：" prop="createDateStr">
              <Input v-model="formData.createDateStr" readonly/>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="所属单位：" prop="orgName">
              <Input v-model="formData.orgName" readonly/>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16">
          <i-col span="24">
            <FormItem label="附件：" prop="zuopin">
              <Upload
                  multiple
                  ref="upload"
                  name="files"
                  accept=".xlsx"
                  :format="['xlsx']"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  :action="fileUrl">
                <div style="padding: 20px 0">
                  <Button icon="ios-cloud-upload-outline">导入报表</Button>
                </div>
              </Upload>
              <ExeclComponent ref="execlComponent" class="execlClass" v-if="modal1"  v-bind:execlSheet="formData.execlSheet"/>
  <!--            <div v-for="(item, index) in fileList" :key="index">
                <a>{{item.name}}</a>
                <Button type="text" icon="md-trash" @click="removeFile(item.keyID)"  style="margin-left: 10px;margin-bottom: 3px"/>
                <Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>
                <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
              <div v-for="(item, index) in modifyFile" :key="index">
                <a @click.prevent="downloadFile(item,index)">{{item.fileName}}</a>
                <Button type="text" icon="md-trash" @click.native="removeFile2(item)"  style="margin-left: 10px;margin-bottom: 3px"/>
              </div> -->
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="saveInfo" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="modal1 = false" class="ivu-btn-cancel" >取消</Button>
      </div>
    </Modal>
    <Modal v-model="modal2" width="1200" :mask-closable="false" title="填报详情">
      <Form ref="formCustom" :model="formData" :rules="ruleCustom" :label-width="100">
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="活动主题：" prop="topicActivityName">
              {{formData.topicActivityName}}
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="编制时间：" prop="createDateStr">
              {{formData.createDteStr}}
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="创建人：" prop="userName">
              {{formData.userName}}
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="联系电话：" prop="mobileNumber">
              {{formData.mobileNumber}}
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16" class="code-row-bg2">
          <i-col span="12">
            <FormItem label="创建时间：" >
              {{formData.createDateStr}}
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="所属单位：" >
              {{formData.orgName}}
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16">
          <i-col span="24">
            <FormItem label="附件：" prop="orgName">
              <ExeclComponent class="execlClass" v-if="modal2"  v-bind:execlSheet="formData.execlSheet"/>
              <div v-for="(item, index) in modifyFile" :key="index">
                <a @click.prevent="downloadFile(item,index)">{{item.fileName}}</a>
                <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="modal2 = false" class="ivu-btn-cancel" >取消</Button>
      </div>
    </Modal>

    <div v-show="downloading"
         style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;background-color:#000000;opacity:0.5;">
      <svg-bar style="position:absolute;top:50%;left:50%;margin-left:-100px;margin-top:-100px"
               :options="options" :value="batchProcess"></svg-bar>
    </div>

  </div>
</template>

<script>
import ExeclComponent from "./execlComponent.vue";
import luckySheetUtil from "./luckySheetUtil.js"
import svgBar from 'svg-progress-bar';
var cascaderDom = () => import('@/components/cascader-dom.vue');
import {sessionStorage} from '@/common/cacheUtils.js';
import {Api} from '@/api/index.js'

export default {
  name: "topicWork",
  components:{
    ExeclComponent,
    cascaderDom,svgBar
  },
  data(){
    const validatePhone = (rule, value, callback) => {
      if(!this.formData.mobileNumber) {
        return callback(new Error('手机号不能为空'));
      } else if(!/^1[345789]\d{9}$/.test(this.formData.mobileNumber)) {
        callback('手机号格式不正确');
      } else {
        callback();
      }
    };
    const validateFile = (rule, value, callback) => {
      if(this.fileList.length == 0) {
        this.$Message.error({ content: '请导入报表', duration: 4});
        return callback(new Error('请导入报表'));
      } else {
        callback();
      }
    };
    return{
      downloading:false,
      batchProcess:0,
      filePercent:[],
      filePercentVisible:[],
      uploadListVisible:[],
      uploadListPercent:[],
      topics:[],
      exportInfos:[],
      ifSpin: false,
      isUpdate:false,
      fileUrl: '',
      buttonLoading: false,
      switchFlag: false,
      tableHeight: '',
      loading: false,
      dataToQuery: {
        se_date: []
      },
      ruleCustom: {
        topicActivityId: [
          {
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
        userName: [
          {
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
        mobileNumber: [
          {
            required: true,
            validator: validatePhone,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
        createDateStr: [
          {
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
        orgName: [
          {
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
        zuopin: [
          {
            required: true,
            validator: validateFile,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
      },
      modal1: false,
      modal2: false,
      titleName: '',
      formData: {},
      currentUser: sessionStorage('userId').getObject('userId'),
      pageSizeArray: [10, 20, 50,100],
      fileList: [],
      modifyFile: [],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
          fixed: 'left',
        },
        {
          title:'活动主题',
          key:'topicActivityName',
          align:'center',
          width: 200,
        },
        {
          title: '所属二级集团',
          align: 'center',
          key: 'twoLevelOrgName',
          minWidth: 200,
          render:(h,params)=>{
            return h('div',[
              h('span',params.row.twoLevelOrgName || '--')
            ]);
          }
        },
        {
          title: '所属单位',
          align: 'center',
          key: 'orgName',
          minWidth: 200,
          render:(h,params)=>{
            return h('div',[
              h('span',params.row.orgName || '--')
            ]);
          }
        },
        {
          title: '创建人',
          align: 'center',
          key: 'userName',
          minWidth: 200,
          render:(h,params)=>{
            return h('div',[
              h('span',params.row.userName || '--')
            ]);
          }
        },
        {
          title: '联系电话',
          align: 'center',
          key: 'mobileNumber',
          minWidth: 200,
          render:(h,params)=>{
            return h('div',[
              h('span',params.row.mobileNumber || '--')
            ]);
          }
        },
        {
          title: '创建时间',
          align: 'center',
          key: 'createDateStr',
          minWidth: 200,
          render:(h,params)=>{
            return h('div',[
              h('span', params.row.createDateStr || '--')
            ]);
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 180,
          render: (h, params) => {
            let flag =(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId  ||
                (this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined))
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.modal2 = true;
                    this.updateInfo(params.row);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'red':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.modal1= true;
                    this.updateInfo(params.row);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'red':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteInfo(params.row);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '删除')
            ]);
          }
        },

      ],
      infos: [],
      reqTopics:[],
      twoLevelOrgList: [],
    }
  },
  computed: {
    options: function() {
      return {
        radius: 50,//大小
        duration: 2,//变化时间长度
        circleWidth: 5,//圆环宽度
        pathColors: ['#A2A2A2', '#FA5657'], //圆环 底色和 上面的颜色
        circleLineCap: 'round',//进度条 形状  圆环 或者矩形
        text: function (value) {
          return this.htmlifyNumber(value) + '<span style="font-size: 0.4em;">%</span>';
        },
        textColor: 'rgb(33, 150, 243)'
      }
    }
  },
  mounted(){
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.queryTwoLevelOrg();
    this.queryTopic();
    this.query();
    this.$Loading.config({
      color: '#5cb85c',
      failedColor: 'red',
      height: 5
    });
  },
  watch: {
    "modal1":function(qw,er){
      if(!qw){
        this.formData = {execlSheet:{}};
        this.fileList = [];
        this.modifyFile = [];
      }
    },
    "modal2":function(qw,er){
      if(!qw){
        this.formData = {};
        this.fileList = [];
        this.modifyFile = [];
      }
    },
  },
  methods: {
    ...luckySheetUtil,
    changeActivity(activityId){
      for(var i=0;i<this.topics.length;i++){
        if(this.topics[i].topicActivityId == activityId){
          this.formData.execlSheet =  this.topics[i].execlSheet;
          this.$refs.execlComponent.initLuckysheet(this.formData.execlSheet);
          return;
        }
      }
    },
    query1() {
      this.pagedata.currentPage = 1;
      this.query()
    },
    query(){
      this.loading = true;
      let data = {
        orgId: this.currentUser.companyId,
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
      }
      if(this.dataToQuery.se_date.length!=0){
        if(this.dataToQuery.se_date[0] != '' && this.dataToQuery.se_date[1] != ''){
          data.startDate = this.formatDate(new Date(this.dataToQuery.se_date[0]), 'yyyy-MM-dd');
          data.endDate = this.formatDate(new Date(this.dataToQuery.se_date[1]), 'yyyy-MM-dd');
        }
      }
      data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
      this.$http.get(Api.topicWorkCustomizeList, {
        params: data
      }).then(function(res){
        this.infos = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }, function(res){
        this.$Message.error('请求失败');
        this.loading = false;
      });
    },
    pageSizeChange(pageSize){
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum){
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    reseter(){
      this.dataToQuery = {
        se_date: []
      };
      setTimeout(() => {
        this.$refs.existOrg.setCurrentOrg();
      }, 100);
      this.query();
    },
    switchQuery(flag){
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    downloadTemplate(){
      for(var i=0;i<this.reqTopics.length;i++) {
        if(this.dataToQuery.topicActivityId == this.reqTopics[i].topicActivityId) {
          this.exportSheetExcel(JSON.parse(this.reqTopics[i].execlSheet), this.reqTopics[i].themeName + "--模板");
        }
      }
    },
    addInfo(){
      this.isUpdate = false;
      this.modal1 = true;
      this.titleName = "新增";
      this.formData = {
        userName: this.currentUser.userName,
        userId: this.currentUser.userId,
        orgName: this.currentUser.companyName,
        orgId: this.currentUser.companyId,
        createUserId: this.currentUser.userId,
        createOrgId:this.currentUser.orgInfo.orgId,
        mobileNumber: this.currentUser.mobileNumber,
        createDate: new Date(),
        createDateStr: this.formatDate(new Date()),
        topicWorkId: this.uuid(),
        twoLevelOrgId: this.currentUser.twoLevelOrgId,
        twoLevelOrgName: this.currentUser.twoLevelOrgName,
        topicActivityId: this.topics.length>0?this.topics[0].topicActivityId:'',
        execlSheet: this.topics.length>0?this.topics[0].execlSheet:null
      };
      this.fileUrl = Api.uploadPTWFiles  + '/' + this.formData.topicWorkId + '/files/file';
      if(this.topics.length == 0){
        this.$Message.error({content :'当前没有符合填报日期的活动主题' , duration: 5});
      }
    },
    batchDownload(){
      this.buttonLoading = true;
      let data = {
        orgId: this.currentUser.companyId,
        startPage: 1,
        size: this.pagedata.total,
      }
      if(this.dataToQuery.se_date.length!=0){
        if(this.dataToQuery.se_date[0] != '' && this.dataToQuery.se_date[1] != ''){
          data.startDate = this.formatDate(new Date(this.dataToQuery.se_date[0]), 'yyyy-MM-dd');
          data.endDate = this.formatDate(new Date(this.dataToQuery.se_date[1]), 'yyyy-MM-dd');
        }
      }
      data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
      this.$http.get(Api.topicWorkCustomizeList, {
        params: data
      }).then(function(res){
        this.buttonLoading = false;
        this.exportInfos = res.data.data.data;
//        this.fileBatchDownload();
        if(this.exportInfos.length > 0) {
          let execlInfo = [];
          var execlSheetHead = "";
          var execlName = "";
          for(var i=0;i<this.reqTopics.length;i++){
            if(this.exportInfos[0].topicActivityId == this.reqTopics[i].topicActivityId){
              execlSheetHead = this.reqTopics[i].execlSheet;
              execlName = this.reqTopics[i].themeName;
              break;
            }
          }
          let headIndex = 0;
          execlInfo = JSON.parse(execlSheetHead);
          for(let x=0;x<execlInfo[0].data.length;x++){
            let items = execlInfo[0].data[x];
            for (let i = 0; i < items.length; i++) {
              if(items[i] != null && items[i].it == 1)
                break;
              if (items[i] != null && items[i].v != undefined) {
                headIndex = x+1;
                break;
              }
            }
          }
          var colIndex = headIndex;
          execlInfo[0].data = execlInfo[0].data.slice(0,headIndex);
          var index = 0;
          this.exportInfos.forEach(item=>{
            let temp = JSON.parse(item.execlSheet);
            let tempIndex = headIndex;
            for(let x=headIndex;x<temp[0].data.length;x++){
              let items = temp[0].data[x];
              for(let i=0;i<items.length;i++){
                if(items[i] != null && items[i].it == 1)
                  break;
                if(items[i] != null && items[i].v != undefined){
                  tempIndex = x+1;
                  break;
                }
              }
            }
            temp[0].data = temp[0].data.slice(headIndex,tempIndex);
            execlInfo[0].data = execlInfo[0].data.concat(temp[0].data)
            console.log(temp[0].data)
            for(var key in temp[0].config.merge) {
              if(colIndex < temp[0].config.merge[key].r){
                execlInfo[0].config.merge[((temp[0].config.merge[key].r+index) + "_" + (temp[0].config.merge[key].c))] =
                    {r:temp[0].config.merge[key].r+index,c:temp[0].config.merge[key].c,
                      rs:temp[0].config.merge[key].rs,cs:temp[0].config.merge[key].cs
                    };
              }
            }
            index += tempIndex - headIndex;
          })
          this.exportSheetExcel(execlInfo, this.exportInfos[0].topicActivityName + "--汇总数据");
        }
      }, function(res){
        console.log(res)
        this.$Message.error('请求失败');
        this.buttonLoading = false;
      });
    },
    fileBatchDownload(){
      this.downloading = true;
      var url = Api.mongoBatchDownload;
      var ids = [];
      var fileNames = [];
      this.exportInfos.forEach(item=>{
        ids.push(item.topicWorkId)
        fileNames.push(item.orgName)
      })
      this.batchProcess = 0;
      var _this = this;
      let formData = new FormData();
      formData.append("ids", ids); // 文件对象
      formData.append("fileNames", fileNames); // 文件对象
      this.$http.post(url, formData, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        downloadProgress:function(e){
          _this.batchProcess = 100 * (e.loaded / e.total);
          if(_this.batchProcess == 100){
            _this.downloading = false;
          }
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: 'application/zip'     //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = this.formatDate(new Date(), 'yyyyMMddhhmmss') + ".zip";
        aLink.click()
        document.body.appendChild(aLink)
      }, function(res){
        this.$Loading.error();
      })
    },
    updateInfo(row){
      this.isUpdate = true;
      this.formData = row;
      this.formData.updateOrgId = this.currentUser.orgInfo.orgId,
          this.formData.updateUserId = this.currentUser.userId;
      this.formData.twoLevelOrgId = this.currentUser.twoLevelOrgId,
          this.titleName = "修改";
      this.fileUrl = Api.uploadPTWFiles  + '/' + this.formData.topicWorkId + '/files/file'
      this.$http.get(this.fileUrl,{
        params: {},
      }).then((res) => {
        var index = 0;
        res.data.data.map((i) =>{
          this.modifyFile.push(i);
          this.uploadListPercent[index]=0;
          this.uploadListVisible[index] = false;
          index++;
        })
      })
    },
    setOrgId(data) {
      this.dataToQuery.orgId= data[data.length - 1];
    },
    setOrgName(data) {
      this.dataToQuery.orgName = data;
    },
    async saveInfo(){
      this.$refs['formCustom'].validate(async(valid) => {
        if(valid) {
          this.buttonLoading = true;
          window.luckysheet.exitEditMode();
          this.formData.execlSheet = this.$refs.execlComponent.getSheetData();
      //    await this.handUpload();
          if(this.isUpdate){
            this.$http.put(Api.topicWorkCustomize, this.formData).then(function(response){
              this.buttonLoading = false;
              this.modal1 = false;
              this.query();
              this.$Message.success({  content: '保存成功', duration: 4 });
            });
          }else{
            this.$http.post(Api.topicWorkCustomize, this.formData).then(function(response){
              this.buttonLoading = false;
              this.modal1 = false;
              this.query();
              this.$Message.success({  content: '保存成功', duration: 4 });
            });
          }
        }
      })
    },
    deleteInfo(row){
        this.$http.delete(Api.topicWorkCustomize + "/" + row.topicWorkId, {params:{
            updateUserId: this.currentUser.userId
          }}).then((res) => {
          this.$Message.success({content: '删除成功', duration: 4});
          this.query();
        })
    },
    beforeUpload (file) {
      if (file == null || file.length == 0) {
        this.$message.warning("文件为空，请重新选择文件");
        return;
      }
      for(var i=0;i<this.topics.length;i++) {
        if(this.topics[i].topicActivityId == this.formData.topicActivityId) {
          this.$refs.execlComponent.importExecl(file, this.topics[i].execlSheet);
//          let keyID = Math.random().toString().substr(2);
//          file['keyID'] = keyID;
//          this.filePercent[this.fileList.length]=0;
//          this.filePercentVisible[this.fileList.length]=false;
//          this.fileList.push(file);
          break;
        }
      }
      return false;
    },
    async handUpload(){
      var index = 0;
      var length = this.fileList.length;
      var _this = this;
      for(var i=0;i<this.fileList.length;i++){
        let formData = new FormData();
        var config = {
          progress: function (e) {
            _this.$set(_this.filePercentVisible,index,true);
            if(e.lengthComputable){
              _this.$set(_this.filePercent,index, 100 * (e.loaded / e.total));
            }
          }
        }
        formData.append("files", this.fileList[i]); // 文件对象
        await this.$http.post(this.fileUrl, formData,config).then((res) => {
          index++
          if (res.data.result == "success" && index == length) {
            this.$Message.info("导入报表成功")
          }
        })
      }
    },
    downloadFile(file,index){
      let url = Api.interestedPartiesUserFile + '/file/' + file.id;
      this.uploadListVisible[index] = true;
      var _this = this;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress:function(e){
          _this.$set(_this.uploadListPercent,index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      }, function(res){
        this.$Loading.error();
      })
    },
    removeFile(keyID){
      this.fileList = this.fileList.filter(item => {
        return item.keyID != keyID
      })
    },
    removeFile2(file){
      this.$http.delete(Api.uploadMongoFile + "/" + file.id).then((res) => {
        this.modifyFile.splice(this.modifyFile.indexOf(file), 1);
      }).catch(e => {
        this.$Message.error("附件删除失败");
      });
    },
    queryTwoLevelOrg(){
      this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
        if(res.data.status == 200){
          this.twoLevelOrgList = res.data.data;
        }
      }).catch(e => {
        this.$Message.error("附件删除失败");
      });
    },
    queryTopic(){
      let data1 = {
        startPage: 1,
        size: 1000,
        orgId:this.currentUser.companyId
      }
      this.$http.get(Api.topicActivityCustomizeList, {
        params: data1
      }).then((res) => {
        if(res.data.status == 200){
          this.reqTopics = res.data.data.data;
          if(this.reqTopics.length > 0){
            this.dataToQuery.topicActivityId = this.reqTopics[0].topicActivityId;
          }
        }
      }).catch(e => {
        this.$Message.error("附件删除失败");
      });
      let data = {
        startPage: 1,
        size: 1000,
        orgId:this.currentUser.companyId,
        currentDay: this.formatDate(new Date(), 'yyyy-MM-dd')
      }
      this.$http.get(Api.topicActivityCustomizeList, {
        params: data
      }).then((res) => {
        if(res.data.status == 200){
          this.topics = res.data.data.data;
        }
      }).catch(e => {
        this.$Message.error("附件删除失败");
      });
    },
    exportFormSubmit(){
      this.buttonLoading = true;
      let data = {
        orgId: this.currentUser.companyId
      }
      if(this.dataToQuery.se_date.length!=0){
        if(this.dataToQuery.se_date[0] != '' && this.dataToQuery.se_date[1] != ''){
          data.startDate = this.formatDate(new Date(this.dataToQuery.se_date[0]), 'yyyy-MM-dd');
          data.endDate = this.formatDate(new Date(this.dataToQuery.se_date[1]), 'yyyy-MM-dd');
        }
      }
      data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
      this.$http.get(Api.topicWorkCustomizeList + '/export',{
        params: data,
        responseType: 'arraybuffer'
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        })
        aLink.href = URL.createObjectURL(blob);
        aLink.download = "作品管理("+ this.formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
        aLink.click();
        document.body.appendChild(aLink);
        this.buttonLoading = false;
      })
    },
    formatDate(date, fmt) {
      if (typeof date == 'string') {
        return date;
      }
      if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
      if (!date || date == null) return null;
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
    uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for(let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      let uuid = s.join("");
      return uuid
    },
  }
}
</script>

<style lang='css' scoped>
@import '../../../index.css';


.modalClass{
  opacity:0.5;
}

.execlClass{
  width:100%;
  height:300px
}
</style>
